#coding=utf-8
from stutils import *
set_django_environ()
from stdj.stock.models import *
import datetime
td = datetime.date.today().isoformat()

def days_between2date(d1, d2):
    d1 = datetime.date( *map(int, d1.split('-')) )
    d2 = datetime.date( *map(int, d2.split('-')) )
    return (d2-d1).days

def top10(share, until, field='end'):
    c = get_dbconnector().cursor()
    c.execute('select * from price where code=? and date <= ? order by %s desc limit 10'%field, 
              (share.code, until)
              )
    data = c.fetchall()
    
    if not data:return None
    
    index = 0
    mds = c.description
    for i in range( len(mds) ):
        if mds[i][0] == field:
            index = i
             
    data = [[d[3].encode('u8'),d[index]] for d in data]
    return data

def newtop(exdate=td):
    '''在交易日exdate创新高的股票.'''
    r = []
    for s in Share.objects.order_by('code'):
        t10 = top10(s, exdate)
        if not t10:continue
        #rule 1
        t3 = t10[:3]
        eds = [i[0] for i in t3]
        n = days_between2date( min(eds), max(eds))
        if n < 15:
            continue
        
        if exdate in eds:
            r.append(s)
    return r 

def afternday_change(exday, n):
    p1 = exday.price.end
    ne = exday.afternday(n)
    if not ne:return None
    p2 = ne.price.end
    
    return float(todec((p2-p1)*100/p1, 2))

if __name__ == "__main__":
    dt = '2008-01-02'
    ss = newtop(dt)
    #print len(ss)
    '''
    for s in ss:
        e = s.exday_set.get(date=dt)
        print s, afternday_change(e, 1),afternday_change(e, 3),afternday_change(e, 5)
        '''
    print ','.join( [s.code for s in ss])